package com.mission.schedule.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import cn.sharesdk.framework.ShareSDK
import cn.sharesdk.onekeyshare.OnekeyShare
import com.android.volley.AuthFailureError
import com.android.volley.DefaultRetryPolicy
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.google.gson.Gson
import com.lidroid.xutils.HttpUtils
import com.lidroid.xutils.exception.HttpException
import com.lidroid.xutils.http.RequestParams
import com.lidroid.xutils.http.ResponseInfo
import com.lidroid.xutils.http.callback.RequestCallBack
import com.lidroid.xutils.http.client.HttpRequest
import com.mission.schedule.CommonDialog.CalenderLYDialog
import com.mission.schedule.CommonDialog.NewSixTaskDetailDialog
import com.mission.schedule.R
import com.mission.schedule.applcation.App
import com.mission.schedule.bean.*
import com.mission.schedule.bean.qd606.NoteTitleDetailBean
import com.mission.schedule.constants.ShareFile
import com.mission.schedule.constants.URLConstants
import com.mission.schedule.entity.ScheduleTable
import com.mission.schedule.service.DownImageService
import com.mission.schedule.service.LocalSynService
import com.mission.schedule.utils.DateUtil
import com.mission.schedule.utils.ProgressUtil
import com.mission.schedule.utils.SharedPrefUtil
import com.mission.schedule.utils.StringUtils
import com.nostra13.universalimageloader.core.DisplayImageOptions
import com.nostra13.universalimageloader.core.ImageLoader
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener
import kotlinx.android.synthetic.main.activity_task_detail.*
import kotlinx.android.synthetic.main.qdfx_de_list_item.view.*
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.util.*

class NewSixTaskDetailActivity : Activity() {

    var schDate = ""
    var schTime = ""
    var schID = ""
    var ID = "0"
    var schSourceDesc = ""
    var schDisplayTime = "0"
    var schIsPostpone = "1"
    var schCreateTime = ""
    var changeTime = ""
    var schContent = ""
    var schIsEnd = "0"

    var title_img = ""
    var pname = ""
    var id = 0

    var time = ""
    var userid = ""
    var username = ""
    var puid = "0"
    var pdelete = 0
    var stylee = 0
    //4 任务链接 5 日程链接
    var schSourceType = "4"
    var schRemark1 = "0"
    var schRemark4 = ""
    var schRemark5 = ""
    var showschID = 0
    var cUid = 0

    var isLocal = 0

    lateinit var share: SharedPrefUtil
    lateinit var context: Context
    lateinit var imageLoader: ImageLoader
    lateinit var animateFirstListener: ImageLoadingListener
    lateinit var options: DisplayImageOptions
    var list2: List<DownNewSixTaskBean.List2Bean> = listOf()
    var list3: List<ClenderUrlBean.List2Bean> = listOf()
    var list4: List<CalenderNoteBean.PageBean.ItemsBean> = listOf()
    var dlistbean = DownNewSixTaskBean.ListBean()
    var clistbean = ClenderUrlBean.ListBean()
    var adapter = ChildAdapter()
    private var dowmTime = ""
    private var schImagePath = ""
    lateinit var recyclerviews: RecyclerView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_task_detail)

        context = this@NewSixTaskDetailActivity
        imageLoader = ImageLoader.getInstance()
        animateFirstListener = AnimateFirstDisplayListener()

        recyclerviews = findViewById(R.id.recyclerview)

        share = SharedPrefUtil(context, ShareFile.USERFILE)

        userid = share.getString(ShareFile.USERID, "")
        username = share.getString(ShareFile.USERNAME, "")
        dowmTime = share.getString(ShareFile.DOWNTASKTIME, "2017-12-20 00:00:00")
        schDate = intent.getStringExtra("schDate")
        schTime = intent.getStringExtra("schTime")
        schID = intent.getStringExtra("schID")
        showschID = schID.toInt()
        ID = intent.getStringExtra("ID")
        schSourceDesc = intent.getStringExtra("schSourceDesc")
        schDisplayTime = intent.getStringExtra("schDisplayTime")
        schIsPostpone = intent.getStringExtra("schIsPostpone")
        schCreateTime = intent.getStringExtra("schCreateTime")
        pname = intent.getStringExtra("schcRecommendName")
        schContent = intent.getStringExtra("schContent")
        puid = intent.getStringExtra("schcRecommendId")
        if (puid == "-2") puid = "0"
        schIsEnd = intent.getStringExtra("schIsEnd")
        schSourceType = intent.getStringExtra("schSourceType")
        title_img = intent.getStringExtra("schImagePath")
        schRemark1 = intent.getStringExtra("schRemark1")
        schRemark4 = intent.getStringExtra("schRemark4")
        schRemark5 = intent.getStringExtra("schRemark5")

        isLocal = 0
        schImagePath = intent.getStringExtra("schImagePath")

        showTitleImage(schImagePath)

        if (schRemark1 == "1") {
            title_img = share.getString(ShareFile.USERPHOTOPATH, "")
            pname = username
        }

        recyclerview.layoutManager = LinearLayoutManager(context)
        recyclerview.adapter = adapter

        options = DisplayImageOptions.Builder()
                .showStubImage(R.mipmap.b1)
                .showImageForEmptyUri(R.mipmap.b1)
                .showImageOnFail(R.mipmap.b1).cacheInMemory(true)
                .cacheOnDisc(true).cacheInMemory(true)
                .bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
                .build()


        setInit()

        loadData()

        getUrlTime()
        updateUrlTime()

        top_ll_back.setOnClickListener {
            onBackPressed()
        }

        top_ll_right.setOnClickListener {
            val tagalog = NewSixTaskDetailDialog(this@NewSixTaskDetailActivity, R.style.dialog_translucent, windowManager)
            tagalog.show()
            tagalog.callBack = object : NewSixTaskDetailDialog.CallBack {
                override fun savenote() {
                    val id = App.getDBcApplication().tiMinId - 1
                    val nettled = DateUtil.nowTime1()
                    val bean = NoteTitleDetailBean.TDelListBean()
                    bean.titleId = nettled
                    bean.uid = userid.toInt()
                    bean.id = id
                    bean.styles = stylee
                    bean.changeTime = DateUtil.nowTime()
                    bean.createTime = DateUtil.nowTime()
                    bean.localTimes = DateUtil.nowTime()
                    bean.ltype = 0
                    bean.orderId = 0
                    bean.copys = "0"
                    bean.filed = "0"
                    bean.titles = schContent
                    bean.imgPath = ""
                    bean.imgUrl = ""
                    bean.nums = ""
                    bean.shareUrl = ""
                    bean.remark = "0"
                    bean.remark1 = "0"
                    bean.remark2 = ""
                    bean.remark3 = ""
                    bean.pname = ""
                    bean.puid = 0
                    bean.states = 0
                    bean.sends = 0
                    bean.openState = 0
                    bean.other1 = "0"

                    App.getDBcApplication().saveNoteTitleData(bean)
                    App.getDBcApplication().updateNoteTitleState(bean.titleId, userid, 1, false)
                    if (isLocal == 1) {
                        list4.forEach {
                            val listBean = NoteTitleDetailBean.ListBean()
                            listBean.titleId = nettled
                            listBean.uid = Integer.valueOf(userid)!!
                            listBean.id = App.getDBcApplication().minId - 1
                            listBean.style = it.style
                            listBean.changetime = DateUtil.nowTime()
                            listBean.createTime = DateUtil.nowTime()
                            listBean.lType = 0
                            listBean.orderId = it.orderId
                            listBean.endstate = it.endstate
                            listBean.remark = ""
                            listBean.contents = it.contents
                            listBean.titles = schContent
                            listBean.imgPath = ""
                            listBean.imgUrl = ""
                            listBean.cpath = ""
                            listBean.curl = ""
                            listBean.nums = ""
                            listBean.shareUrl = ""
                            listBean.remark1 = ""
                            listBean.remark2 = ""
                            listBean.remark3 = ""
                            listBean.remark4 = ""

                            App.getDBcApplication().saveNoteDetailData(listBean)
                            App.getDBcApplication().updateNoteTitleDetailState(nettled, listBean.id, userid, 1, false)
                        }
                    } else {
                        if (schSourceType == "5" || schRemark1 == "1") {
                            list3.forEach {
                                val listBean = NoteTitleDetailBean.ListBean()
                                listBean.titleId = nettled
                                listBean.uid = Integer.valueOf(userid)!!
                                listBean.id = App.getDBcApplication().minId - 1
                                listBean.style = it.style
                                listBean.changetime = DateUtil.nowTime()
                                listBean.createTime = DateUtil.nowTime()
                                listBean.lType = 0
                                listBean.orderId = it.orderId
                                listBean.endstate = it.endstate
                                listBean.remark = ""
                                listBean.contents = it.contents
                                listBean.titles = schContent
                                listBean.imgPath = ""
                                listBean.imgUrl = ""
                                listBean.cpath = ""
                                listBean.curl = ""
                                listBean.nums = ""
                                listBean.shareUrl = ""
                                listBean.remark1 = ""
                                listBean.remark2 = ""
                                listBean.remark3 = ""
                                listBean.remark4 = ""

                                App.getDBcApplication().saveNoteDetailData(listBean)
                                App.getDBcApplication().updateNoteTitleDetailState(nettled, listBean.id, userid, 1, false)
                            }
                        } else {
                            list2.forEach {
                                val listBean = NoteTitleDetailBean.ListBean()
                                listBean.titleId = nettled
                                listBean.uid = Integer.valueOf(userid)!!
                                listBean.id = App.getDBcApplication().minId - 1
                                listBean.style = it.style
                                listBean.changetime = DateUtil.nowTime()
                                listBean.createTime = DateUtil.nowTime()
                                listBean.lType = 0
                                listBean.orderId = it.orderId
                                listBean.endstate = it.endstate
                                listBean.remark = ""
                                listBean.contents = it.contents
                                listBean.titles = schContent
                                listBean.imgPath = ""
                                listBean.imgUrl = ""
                                listBean.cpath = ""
                                listBean.curl = ""
                                listBean.nums = ""
                                listBean.shareUrl = ""
                                listBean.remark1 = ""
                                listBean.remark2 = ""
                                listBean.remark3 = ""
                                listBean.remark4 = ""

                                App.getDBcApplication().saveNoteDetailData(listBean)
                                App.getDBcApplication().updateNoteTitleDetailState(nettled, listBean.id, userid, 1, false)
                            }
                        }
                    }
                    val pull = Intent()
                    pull.action = "pullRecevier"
                    sendBroadcast(pull)
                    Toast.makeText(context, "已保存", Toast.LENGTH_SHORT).show()
                }

                override fun weixin() {
                    if (share.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0") == "-1") {
//                        localSyn()
//                        var api = WXAPIFactory.createWXAPI(this@NewSixTaskDetailActivity, "wx5add723149fa57f5")
//                        var miniProgram = WXMiniProgramObject()
//                        miniProgram.webpageUrl = "http://www.keytimeapp.com"//自定义
//                        miniProgram.userName = "gh_f297c56cae16"//小程序端提供参数
//                        miniProgram.path = "pages/schedule/schedule?uid=$puid&titleId=$schSourceDesc&id=$showschID&name=$pname&img=$title_img"//小程序端提供参数
//                        var mediaMessage = WXMediaMessage(miniProgram)
//                        mediaMessage.title = schContent//自定义
//                        mediaMessage.description = schContent//自定义
//                        val dice = Environment.getExternalStorageDirectory().toString() + "/DCIM/"
//                        val outfile = File(dice, "TimeApp")
//                        var bitmap = BitmapFactory.decodeFile("$outfile/${title_img.replace('/', '0')}")
//                        if (bitmap == null) {
//                            bitmap = BitmapFactory.decodeResource(resources, R.mipmap.logo);
//                        }
//                        mediaMessage.thumbData = Util.bmpToByteArray(bitmap, true)
//                        bitmap.recycle()
//                        var req = SendMessageToWX.Req()
//                        req.transaction = ""
//                        req.scene = SendMessageToWX.Req.WXSceneSession
//                        req.message = mediaMessage
//                        api.sendReq(req)
//                        val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
//                        // 将文本内容放到系统剪贴板里。
//                        cm.text = "pages/schedule/schedule?uid=$puid&titleId=$schSourceDesc&id=$showschID&name=$pname&img=$title_img"

                        ShareSDK.initSDK(context)
                        val oks = OnekeyShare()
                        // 关闭sso授权
                        oks.disableSSOWhenAuthorize()
                        oks.setTitle(schContent)

                        if (schSourceType == "5" || schRemark1 == "1") {
                            oks.text = if (list3.isNotEmpty()) list3[0].contents else schContent
                        } else {
                            oks.text = if (list2.isNotEmpty()) list2[0].contents else schContent
                        }

                        var url = if ((puid == "0" || puid == userid) && schRemark1 == "1" && schSourceType != "5") {
                            "http://www.keytimeapp.com/qingdan/sharingPage.html?uid=$userid&titleId=$schSourceDesc"
                        } else {
                            "http://www.keytimeapp.com/qingdan/qdlist-fx.html?uid=$puid\$titleId=$schSourceDesc" +
                                    "\$id=$showschID\$name=$pname\$img=$title_img"
                        }
                        oks.setUrl(url)
                        oks.setImageUrl("${URLConstants.图片 + share.getString(context,
                                ShareFile.USERFILE, ShareFile.USERPHOTOPATH, "")}&imageType=2&imageSizeType=3")
                        // 启动分享GUI
                        oks.show(context)
                    } else {
                        val newt = Intent(context, PhoneCodeLoginActivity::class.java)
                        newt.putExtra("type", 1)
                        newt.putExtra("login", true)
                        startActivity(newt)
                    }
                }

                override fun copyall() {
                    var cantonment = "**$schContent**"
                    var isOrder = false
                    if (isLocal == 1) {
                        list4.forEach {
                            //                            when (stylee) {
//                                0 -> cantonment += "\n\n□ " + it.contents
//                                1 -> cantonment += "\n\n• " + it.contents
//                                2 -> {
//                                    if (it.orderId == 0) {
//                                        isOrder = true
//                                    }
//                                    cantonment += if (isOrder) {
//                                        "\n\n${it.orderId + 1}." + it.contents
//                                    } else {
//                                        "\n\n${it.orderId}." + it.contents
//                                    }
//                                }
                            //3 ->
                            cantonment += "\n\n" + it.contents
//                            }
                        }
                    } else {
                        if (schSourceType == "5" || schRemark1 == "1") {
                            list3.forEach {
                                when (stylee) {
                                    0 -> cantonment += "\n\n□ " + it.contents
                                    1 -> cantonment += "\n\n• " + it.contents
                                    2 -> {
                                        if (it.orderId == 0) {
                                            isOrder = true
                                        }
                                        cantonment += if (isOrder) {
                                            "\n\n${it.orderId + 1}." + it.contents
                                        } else {
                                            "\n\n${it.orderId}." + it.contents
                                        }
                                    }
                                    3 -> cantonment += "\n\n" + it.contents
                                }
                            }
                        } else {
                            list2.forEach {
                                when (stylee) {
                                    0 -> cantonment += "\n\n□ " + it.contents
                                    1 -> cantonment += "\n\n• " + it.contents
                                    2 -> {
                                        if (it.orderId == 0) {
                                            isOrder = true
                                        }
                                        cantonment += if (isOrder) {
                                            "\n\n${it.orderId + 1}." + it.contents
                                        } else {
                                            "\n\n${it.orderId}." + it.contents
                                        }
                                    }
                                    3 -> cantonment += "\n\n" + it.contents
                                }
                            }
                        }
                    }
                    val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                    cm.text = cantonment
                    Toast.makeText(context, "已复制", Toast.LENGTH_SHORT).show()
                }

                override fun copy() {
                    TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
                }

                override fun share() {
                    val intent = Intent(this@NewSixTaskDetailActivity, SelectionFirendActivity::class.java)
                    if (puid == userid && schRemark1 == "1") {
                        localSyn()
                        intent.putExtra("schSourceType", "99")
                        intent.putExtra("schRemark1", schRemark1)
                        intent.putExtra("updateState", "1")
                        intent.putExtra("schID", schID)
                    } else {
                        intent.putExtra("schSourceType", schSourceType)
                        intent.putExtra("schRemark1", schRemark1)
                        intent.putExtra("updateState", "1")
                        intent.putExtra("schID", schID)

                        if (schSourceType == "5" || schRemark1 == "1") {
                            intent.putExtra("bean", clistbean)
                        } else {
                            intent.putExtra("bean", dlistbean)
                        }
                    }
                    intent.putExtra("titleid", schSourceDesc)
                    intent.putExtra("titles", "")
                    intent.putExtra("remark6", "")
                    intent.putExtra("remark5", "")
                    startActivity(intent)
                }

            }
        }

        code.setOnClickListener {
            val map = App.getDBcApplication().querayOneCalenderData(schID.toInt())
            val cintent = Intent(context, CalenderNoteEditActivity::class.java)
            cintent.putExtra("lingshengnames", map[ScheduleTable.schRingDesc])
            cintent.putExtra("lingshengcode", map[ScheduleTable.schRingCode])
            cintent.putExtra("schTime", map[ScheduleTable.schTime])
            cintent.putExtra("schDate", map[ScheduleTable.schDate])
            cintent.putExtra("schIsAlarm", map[ScheduleTable.schIsAlarm])
            cintent.putExtra("schBeforeTime", map[ScheduleTable.schBeforeTime])
            cintent.putExtra("schDisplayTime", map[ScheduleTable.schDisplayTime])
            cintent.putExtra("schIsPostpone", map[ScheduleTable.schIsPostpone])
            cintent.putExtra("content", map[ScheduleTable.schContent])
            cintent.putExtra("schSourceDesc", map[ScheduleTable.schSourceDesc])
            cintent.putExtra("schImagePath", map[ScheduleTable.schImagePath])
            cintent.putExtra("schID", map[ScheduleTable.schID])
            cintent.putExtra("schIsEnd", map[ScheduleTable.schIsEnd])
            cintent.putExtra("schRepeatID", map[ScheduleTable.schRepeatID])
            cintent.putExtra("schRemark1", StringUtils.getIsStringEqulesNull(map[ScheduleTable.schRemark1]))
            startActivityForResult(cintent, 100)
        }

    }

    override fun onBackPressed() {
        super.onBackPressed()
        App.getDBcApplication().saveCalenderNoteData(schSourceDesc, adapter.nums())
        if (schRemark1 == "1") {
            localSyn()
        }
    }

    private fun localSyn() {
        if (isLocal == 1) {
            val service = Intent(context, LocalSynService::class.java)
            service.action = "LocalSynService"
            service.putExtra("isMinLocal", true)
            service.`package` = context.packageName
            context.startService(service)
        }
    }

    override fun onResume() {
        super.onResume()
        if (isLocal == 0) {
            loadData()
        }
    }

    private fun setInit() {

        time = schDate

        if (schDisplayTime == "0") {
            time += "  全天"
        }

        if (schIsPostpone == "1") {
            time += "  顺"
        }

        val imageUrl = URLConstants.图片 + title_img + "&imageType=2&imageSizeType=3"

        time_type.text = time
        head_name.text = "@$pname"
//        var state = ""
//        if (schIsEnd == "1") state = " 已结束"
//        if (pdelete == 1) state = " 已删除"
//        if (schSourceType == "5" || schRemark1 == "1") {
//            title_type.text = "链接 #$showschID"
//            ide.text = "日程:#$showschID"
//        } else {
//            title_type.text = "@$username #$id$state"

        if (schID.isNotEmpty()) {
            ide.visibility = View.VISIBLE
            ide.text = "日程:#$schID"
        }
//        }

        content.text = schContent
        create_time.text = "创建时间: ${schCreateTime.replace('T', ' ')}"

        imageLoader.displayImage(imageUrl, head_img, options, animateFirstListener)

        if ((puid == "0" || puid == "-2" || puid == userid) && schRemark1 == "1") {
            code.visibility = View.VISIBLE
        }

        if (schRemark5.isNotEmpty() && schRemark5 != "0") {
            uuid_name.visibility = View.VISIBLE
            uuid_name.text = "负责人=$schRemark5"
            if ((puid == "0" || puid == "-2" || puid == userid) && schRemark1 == "1") {
                uuid_name.text = "负责人=$schRemark5(可更换)"
                uuid_name.setOnClickListener {
                    val intent = Intent(this@NewSixTaskDetailActivity, SelectionFirendActivity::class.java)
                    if (puid == userid && schRemark1 == "1") {
                        localSyn()
                        intent.putExtra("schSourceType", "99")
                        intent.putExtra("schRemark1", schRemark1)
                        intent.putExtra("updateState", "2")
                        intent.putExtra("schID", schID)
                    } else {
                        intent.putExtra("schSourceType", schSourceType)
                        intent.putExtra("schRemark1", schRemark1)
                        intent.putExtra("updateState", "2")
                        intent.putExtra("schID", schID)

                        if (schSourceType == "5" || schRemark1 == "1") {
                            intent.putExtra("bean", clistbean)
                        } else {
                            intent.putExtra("bean", dlistbean)
                        }
                    }
                    intent.putExtra("titleid", schSourceDesc)
                    intent.putExtra("titles", "")
                    intent.putExtra("remark6", "")
                    intent.putExtra("remark5", "")
                    startActivity(intent)
                }
            }
        } else {
            uuid_name.visibility = View.VISIBLE
        }


        click_ly.setOnClickListener {
            val lyDialog = CalenderLYDialog(context, R.style.dialog_translucent,
                    windowManager, schContent, schSourceDesc, id.toString(), cUid.toString())
            lyDialog.setCallBack {
                load()
            }
            lyDialog.show()
        }

        listview.setOnItemClickListener { parent, view, position, id ->
            alterImportantDialog(context, itemsBeanList[position].mess, 1, position)
        }
    }

    private fun showTitleImage(path: String?) {
        if (path != null) {
            if (path != "") {
                val dice = Environment.getExternalStorageDirectory().toString() + "/DCIM/"
                val outfile = File(dice, "TimeApp")
                // 如果文件不存在，则创建一个新文件
                if (!outfile.isDirectory) {
                    try {
                        outfile.mkdir()
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }

                }

                val bitmap = BitmapFactory.decodeFile("$outfile/${path.replace('/', '0')}")

                if (bitmap == null) {
                    val options = DisplayImageOptions.Builder()
                            .showStubImage(R.mipmap.loads)          // 设置图片下载期间显示的图片
                            .showImageForEmptyUri(R.mipmap.loads)  // 设置图片Uri为空或是错误的时候显示的图片
                            .showImageOnFail(R.mipmap.loads)       // 设置图片加载或解码过程中发生错误显示的图片
                            .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                            .cacheOnDisc(true)                          // 设置下载的图片是否缓存在SD卡中
                            .build()
                    val imageUrl = URLConstants.图片 + path + "&imageType=15&imageSizeType=1"
                    ImageLoader.getInstance().displayImage(imageUrl, header_image, options)
                    Handler().postDelayed({ ImageLoader.getInstance().displayImage(imageUrl, header_image, options) }, 2000)
                    val intent = Intent(context, DownImageService::class.java)
                    intent.action = "downimage"
                    intent.putExtra("url", imageUrl)
                    intent.putExtra("name", path.replace('/', '0'))
                    startService(intent)
                } else {
                    header_image.setImageBitmap(bitmap)
                }

                header_image.visibility = View.VISIBLE
            } else {
                header_image.visibility = View.GONE
            }
        } else {
            header_image.visibility = View.GONE
        }
    }

    private fun loadData() {
        var loaders = ProgressUtil()
        loaders.ShowProgress(context, true, true, "正在下载...")
        val request3 = object : StringRequest(Method.POST, if (schSourceType == "5" || schRemark1 == "1") URLConstants.下行链接具体信息 else URLConstants.任务下行, Response.Listener { s ->
            if (!TextUtils.isEmpty(s)) {
                try {
                    val goon = Gson()
                    if (schSourceType == "5" || schRemark1 == "1") {
                        val textBean = goon.fromJson(s, ClenderUrlBean::class.java)
                        if (textBean.status == 0) {
                            val listBeanList = textBean.list
                            list3 = textBean.list2 ?: listOf()
                            if (listBeanList != null) {
                                for (bean in listBeanList) {
                                    clistbean = bean
                                    clistbean.cRecommendId = puid.toInt()
                                    clistbean.cRecommendName = pname
                                    title_img = bean.imgPath
                                    schContent = bean.cContent
                                    schDate = bean.cDate
                                    schTime = bean.cTime
                                    schDisplayTime = bean.cDisplayAlarm.toString()
                                    schIsPostpone = bean.cPostpone.toString()
                                    stylee = bean.cLightAppID.toInt()
                                    showschID = bean.cId
                                    schCreateTime = bean.cCreateTime.replace('T', ' ')
                                    changeTime = bean.cUpdateTime.replace('T', ' ')
                                    cUid = bean.cUid

                                    if (schSourceType == "5") {
                                        App.getDBcApplication().updataTaskScheduleData(
                                                ID.toInt(), schID.toInt(), bean.cContent,
                                                bean.cDate, bean.cTime, Integer.valueOf(bean.cIsAlarm)!!, bean.cBeforTime,
                                                bean.cDisplayAlarm, bean.cPostpone, bean.cImportant, bean.cColorType, bean.pIsEnd,
                                                bean.cCreateTime.replace('T', ' '), "", 5, bean.cTypeDesc, bean.cLightAppID.toString() + "", 0, "", "",
                                                1, 0, 0, bean.cAlarmSoundDesc, bean.cAlarmSound, pname, 0, 0, 0, "",
                                                title_img, 0, 0, puid.toInt(), bean.cIsEnd)
                                    }

                                    setInit()
                                }
                            }

                            if (list3.isNotEmpty()) {
                                Collections.sort(list3) { arg0, arg1 -> arg0.orderId.compareTo(arg1.orderId) }
                                adapter.notifyDataSetChanged()
                                App.getDBcApplication().saveCalenderNoteData(schSourceDesc, adapter.nums())
                            }
                        }
                    } else {
                        val textBean = goon.fromJson(s, DownNewSixTaskBean::class.java)
                        if (textBean.status == 0) {
                            val listBeanList = textBean.list
                            list2 = textBean.list2 ?: listOf()
                            if (listBeanList != null) {
                                for (bean in listBeanList) {
                                    dlistbean = bean
                                    title_img = bean.titleImg
                                    schContent = bean.content
                                    schDate = bean.cdate
                                    schTime = bean.ctime
                                    schDisplayTime = bean.cdisplayAlarm.toString()
                                    schIsPostpone = bean.cpostpone.toString()
                                    id = bean.id
                                    pname = bean.uname
                                    username = bean.pname
                                    pdelete = bean.pdeleState
                                    schIsEnd = bean.pIsEnd.toString()
                                    stylee = bean.styles
                                    schIsEnd = bean.cisEnd.toString()
                                    schCreateTime = bean.createTime.replace('T', ' ')
                                    changeTime = bean.changTime.replace('T', ' ')
                                    cUid = bean.puId

                                    App.getDBcApplication().updataTaskScheduleData(
                                            ID.toInt(), schID.toInt(), bean.content,
                                            bean.cdate, bean.ctime, Integer.valueOf(bean.cisAlarm)!!, bean.cbeforTime,
                                            bean.cdisplayAlarm, bean.cpostpone, bean.cimportant, bean.ccolorType, bean.pIsEnd,
                                            bean.createTime.replace('T', ' '), "", bean.ptype + 3, bean.titleId, bean.styles.toString() + "", 0, "", "",
                                            1, 0, 0, bean.calarmSoundDesc, bean.calarmSound, bean.uname, 0, 0, 0, "",
                                            title_img, 0, 0, bean.uid, bean.cisEnd)

                                    setInit()
                                }
                            }

                            if (list2.isNotEmpty()) {
                                Collections.sort(list2) { arg0, arg1 -> arg0.orderId.compareTo(arg1.orderId) }
                                adapter.notifyDataSetChanged()
                                App.getDBcApplication().saveCalenderNoteData(schSourceDesc, adapter.nums())
                            }
                        }
                    }
                    load()
                } catch (e: Exception) {
                    e.printStackTrace()
                }

            }
            if (changeTime.isNotEmpty()) {
                changge_time.text = "最近修改时间  $changeTime  $pname"
            }
            loaders.dismiss()
        }, Response.ErrorListener {
            loaders.dismiss()
        }) {
            @Throws(AuthFailureError::class)
            override fun getParams(): Map<String, String> {
                val map = HashMap<String, String>()
                if (schSourceType == "5" || schRemark1 == "1") {
                    map["uid"] = if (schRemark1 == "1") userid else puid
                    map["titleId"] = schSourceDesc
                } else {
                    map["uid"] = puid
                    map["cpId"] = userid
                    map["downTime"] = ""
                    map["titleId"] = schSourceDesc
                    map["type"] = "3"
                }
                return map
            }
        }
        request3.tag = "downSixTaskCalender"
        request3.retryPolicy = DefaultRetryPolicy(5000, 1, 1.0f)
        App.getHttpQueues().add(request3)
    }

    /**
     * 图片加载第一次显示监听器
     *
     * @author Administrator
     */
    private class AnimateFirstDisplayListener : SimpleImageLoadingListener() {

        override fun onLoadingComplete(imageUri: String, view: View?,
                                       loadedImage: Bitmap?) {
            if (loadedImage != null) {
                val imageView = view as ImageView?
                // 是否第一次显示
                val firstDisplay = !displayedImages.contains(imageUri)
                if (firstDisplay) {
                    // 图片淡入效果
                    FadeInBitmapDisplayer.animate(imageView, 500)
                    displayedImages.add(imageUri)
                }
            }
        }

        companion object {

            internal val displayedImages: MutableList<String> = Collections.synchronizedList(LinkedList())
        }
    }

    inner class ChildAdapter : RecyclerView.Adapter<ChildAdapter.Holder>() {

        override fun getItemCount(): Int {
            return if (isLocal == 1) list4.size else if (schSourceType == "5" || schRemark1 == "1") list3.size else list2.size
        }

        fun nums(): String {
            var tick1 = 0
            var tick2 = 0
            val s: String
            if (isLocal == 1) {
                for (listBean in list4) {
                    if (listBean.endstate == 1) {
                        tick1 += 1
                    }
                    if (listBean.endstate == 2) {
                        tick2 += 1
                    }
                }
                s = if (stylee == 0) {
                    if (list4.isEmpty()) {
                        "0"
                    } else {
                        tick1.toString() + "/" + list4.size
                    }
                } else if (stylee == 4) {
                    if (list4.isEmpty()) {
                        "0"
                    } else {
                        tick1.toString() + "/" + tick2 + "/" + list4.size
                    }
                } else {
                    list4.size.toString()
                }
            } else {
                if (schSourceType == "5" || schRemark1 == "1") {
                    for (listBean in list3) {
                        if (listBean.endstate == 1) {
                            tick1 += 1
                        }
                        if (listBean.endstate == 2) {
                            tick2 += 1
                        }
                    }
                    s = if (stylee == 0) {
                        if (list3.isEmpty()) {
                            "0"
                        } else {
                            tick1.toString() + "/" + list3.size
                        }
                    } else if (stylee == 4) {
                        if (list3.isEmpty()) {
                            "0"
                        } else {
                            tick1.toString() + "/" + tick2 + "/" + list3.size
                        }
                    } else {
                        list3.size.toString()
                    }
                } else {
                    for (listBean in list2) {
                        if (listBean.endstate == 1) {
                            tick1 += 1
                        }
                        if (listBean.endstate == 2) {
                            tick2 += 1
                        }
                    }

                    s = if (stylee == 0) {
                        if (list2.isEmpty()) {
                            "0"
                        } else {
                            tick1.toString() + "/" + list2.size
                        }
                    } else if (stylee == 4) {
                        if (list2.isEmpty()) {
                            "0"
                        } else {
                            tick1.toString() + "/" + tick2 + "/" + list2.size
                        }
                    } else {
                        list2.size.toString()
                    }

                }
            }


            return s
        }

        fun updateEndstate(position: Int, endstate: Int) {
            list2[position].endstate = endstate
            notifyItemChanged(position)
        }

        @SuppressLint("SetTextI18n")
        override fun onBindViewHolder(holder: ChildAdapter.Holder, position: Int) {
            if (isLocal == 1) {
                if (list4.isNotEmpty()) {
                    holder.itemView.ll.setOnClickListener {
                        if (schSourceType == "3") {
                            if (holder.itemView.ch.visibility == View.VISIBLE) {
                                val estate = if (list4[position].endstate == 0) 1 else 0
                                list4[position].endstate = estate
                                App.getDBcApplication().updateCalenderNoteDetailEndstate(list4[position].id, estate, schSourceDesc, userid, true)
                            } else if (holder.itemView.santai.visibility == View.VISIBLE) {
                                val estate = list4[position].endstate
                                when (estate) {
                                    0 -> {
                                        list4[position].endstate = 1
                                        App.getDBcApplication().updateCalenderNoteDetailEndstate(list4[position].id, 1, schSourceDesc, userid, true)
                                    }
                                    1 -> {
                                        list4[position].endstate = 2
                                        App.getDBcApplication().updateCalenderNoteDetailEndstate(list4[position].id, 2, schSourceDesc, userid, true)
                                    }
                                    2 -> {
                                        list4[position].endstate = 0
                                        App.getDBcApplication().updateCalenderNoteDetailEndstate(list4[position].id, 0, schSourceDesc, userid, true)
                                    }
                                }
                            }
                            uploadCalendernote(list4[position].id)
                        }
                        notifyItemChanged(position)
                    }
                    when (stylee) {
                        0 -> {
                            holder.itemView.ll.visibility = View.VISIBLE
                            holder.itemView.ch.visibility = View.VISIBLE
                            if (list4[position].endstate == 0) {
                                holder.itemView.ch.background = resources.getDrawable(R.mipmap.btn_qd_unfinish_c)
                            } else {
                                holder.itemView.ch.background = resources.getDrawable(R.mipmap.btn_qd_finish_c)
                            }
                            holder.itemView.dd.visibility = View.GONE
                            holder.itemView.xh.visibility = View.GONE
                            holder.itemView.santai.visibility = View.GONE
                        }
                        1 -> {
                            holder.itemView.ll.visibility = View.VISIBLE
                            holder.itemView.ch.visibility = View.GONE
                            holder.itemView.dd.visibility = View.VISIBLE
                            holder.itemView.xh.visibility = View.GONE
                            holder.itemView.santai.visibility = View.GONE
                        }
                        2 -> {
                            holder.itemView.ll.visibility = View.VISIBLE
                            holder.itemView.ch.visibility = View.GONE
                            holder.itemView.dd.visibility = View.GONE
                            holder.itemView.xh.visibility = View.VISIBLE
                            holder.itemView.santai.visibility = View.GONE
                        }
                        3 -> {
                            holder.itemView.ch.visibility = View.GONE
                            holder.itemView.dd.visibility = View.GONE
                            holder.itemView.xh.visibility = View.GONE
                            holder.itemView.ll.visibility = View.GONE
                            holder.itemView.santai.visibility = View.GONE
                            holder.itemView.emty_v.visibility = View.VISIBLE
                        }
                        4 -> {
                            holder.itemView.ch.visibility = View.GONE
                            holder.itemView.dd.visibility = View.GONE
                            holder.itemView.xh.visibility = View.GONE
                            holder.itemView.ll.visibility = View.VISIBLE
                            holder.itemView.santai.visibility = View.VISIBLE
                            when {
                                list4[position].endstate == 0 -> holder.itemView.santai.background = resources.getDrawable(R.mipmap.icon_santai1)
                                list4[position].endstate == 1 -> holder.itemView.santai.background = resources.getDrawable(R.mipmap.icon_santai2)
                                else -> holder.itemView.santai.background = resources.getDrawable(R.mipmap.icon_santai3)
                            }
                        }
                    }

                    setcolor(list4[position].contents, holder.itemView.content_tv)
                    holder.itemView.xh.text = "${position + 1}."
                }
            } else {
                if (schSourceType == "5" || schRemark1 == "1") {
                    if (list3.isNotEmpty()) {
                        holder.itemView.ll.setOnClickListener {
                            if (schSourceType == "3") {//||schRemark1 == "1"
                                if (holder.itemView.ch.visibility == View.VISIBLE) {
                                    val estate = if (list3[position].endstate == 0) 1 else 0
                                    clickEndstate(position, estate, list3[position].id, 0, holder.itemView.ch)
                                } else if (holder.itemView.santai.visibility == View.VISIBLE) {
                                    val estate = list3[position].endstate
                                    when (estate) {
                                        0 -> clickEndstate(position, 1, list3[position].id, 1, holder.itemView.santai)
                                        1 -> clickEndstate(position, 2, list3[position].id, 1, holder.itemView.santai)
                                        2 -> clickEndstate(position, 0, list3[position].id, 1, holder.itemView.santai)
                                    }
                                }
                            }
                            if (schRemark1 == "1") {
                                if (holder.itemView.ch.visibility == View.VISIBLE) {
                                    val estate = if (list3[position].endstate == 0) 1 else 0
                                    list3[position].endstate = estate
                                    if (estate == 0) {
                                        holder.itemView.ch.background = resources.getDrawable(R.mipmap.btn_qd_unfinish_c)
                                    } else {
                                        holder.itemView.ch.background = resources.getDrawable(R.mipmap.btn_qd_finish_c)
                                    }
                                    App.getDBcApplication().updateCalenderNoteDetailEndstate(list3[position].id, estate, schSourceDesc, userid, true)
                                } else if (holder.itemView.santai.visibility == View.VISIBLE) {
                                    val estate = list3[position].endstate
                                    when (estate) {
                                        0 -> {
                                            list3[position].endstate = 1
                                            App.getDBcApplication().updateCalenderNoteDetailEndstate(list3[position].id, 1, schSourceDesc, userid, true)
                                        }
                                        1 -> {
                                            list3[position].endstate = 2
                                            App.getDBcApplication().updateCalenderNoteDetailEndstate(list3[position].id, 2, schSourceDesc, userid, true)
                                        }
                                        2 -> {
                                            list3[position].endstate = 0
                                            App.getDBcApplication().updateCalenderNoteDetailEndstate(list3[position].id, 0, schSourceDesc, userid, true)
                                        }
                                    }
                                    when (estate) {
                                        0 -> holder.itemView.santai.background = resources.getDrawable(R.mipmap.icon_santai1)
                                        1 -> holder.itemView.santai.background = resources.getDrawable(R.mipmap.icon_santai2)
                                        else -> holder.itemView.santai.background = resources.getDrawable(R.mipmap.icon_santai3)
                                    }
                                }
                                uploadCalendernote(list3[position].id)
                            }
                        }
                        when (stylee) {
                            0 -> {
                                holder.itemView.ll.visibility = View.VISIBLE
                                holder.itemView.ch.visibility = View.VISIBLE
                                if (list3[position].endstate == 0) {
                                    holder.itemView.ch.background = resources.getDrawable(R.mipmap.btn_qd_unfinish_c)
                                } else {
                                    holder.itemView.ch.background = resources.getDrawable(R.mipmap.btn_qd_finish_c)
                                }
                                holder.itemView.dd.visibility = View.GONE
                                holder.itemView.xh.visibility = View.GONE
                                holder.itemView.santai.visibility = View.GONE
                            }
                            1 -> {
                                holder.itemView.ll.visibility = View.VISIBLE
                                holder.itemView.ch.visibility = View.GONE
                                holder.itemView.dd.visibility = View.VISIBLE
                                holder.itemView.xh.visibility = View.GONE
                                holder.itemView.santai.visibility = View.GONE
                            }
                            2 -> {
                                holder.itemView.ll.visibility = View.VISIBLE
                                holder.itemView.ch.visibility = View.GONE
                                holder.itemView.dd.visibility = View.GONE
                                holder.itemView.xh.visibility = View.VISIBLE
                                holder.itemView.santai.visibility = View.GONE
                            }
                            3 -> {
                                holder.itemView.ch.visibility = View.GONE
                                holder.itemView.dd.visibility = View.GONE
                                holder.itemView.xh.visibility = View.GONE
                                holder.itemView.ll.visibility = View.GONE
                                holder.itemView.santai.visibility = View.GONE
                                holder.itemView.emty_v.visibility = View.VISIBLE
                            }
                            4 -> {
                                holder.itemView.ch.visibility = View.GONE
                                holder.itemView.dd.visibility = View.GONE
                                holder.itemView.xh.visibility = View.GONE
                                holder.itemView.ll.visibility = View.VISIBLE
                                holder.itemView.santai.visibility = View.VISIBLE
                                when {
                                    list3[position].endstate == 0 -> holder.itemView.santai.background = resources.getDrawable(R.mipmap.icon_santai1)
                                    list3[position].endstate == 1 -> holder.itemView.santai.background = resources.getDrawable(R.mipmap.icon_santai2)
                                    else -> holder.itemView.santai.background = resources.getDrawable(R.mipmap.icon_santai3)
                                }
                            }
                        }

                        setcolor(list3[position].contents, holder.itemView.content_tv)
                        holder.itemView.xh.text = "${position + 1}."
                    }
                } else {
                    if (list2.isNotEmpty()) {
                        holder.itemView.ll.setOnClickListener {
                            if (schSourceType == "3") {
                                if (holder.itemView.ch.visibility == View.VISIBLE) {
                                    val estate = if (list2[position].endstate == 0) 1 else 0
                                    clickEndstate(position, estate, list2[position].id, 0, holder.itemView.ch)
                                } else if (holder.itemView.santai.visibility == View.VISIBLE) {
                                    val estate = list2[position].endstate
                                    when (estate) {
                                        0 -> clickEndstate(position, 1, list2[position].id, 1, holder.itemView.santai)
                                        1 -> clickEndstate(position, 2, list2[position].id, 1, holder.itemView.santai)
                                        2 -> clickEndstate(position, 0, list2[position].id, 1, holder.itemView.santai)
                                    }
                                }
                            }
                        }
                        when (stylee) {
                            0 -> {
                                holder.itemView.ll.visibility = View.VISIBLE
                                holder.itemView.ch.visibility = View.VISIBLE
                                if (list2[position].endstate == 0) {
                                    holder.itemView.ch.background = resources.getDrawable(R.mipmap.btn_qd_unfinish_c)
                                } else {
                                    holder.itemView.ch.background = resources.getDrawable(R.mipmap.btn_qd_finish_c)
                                }
                                holder.itemView.dd.visibility = View.GONE
                                holder.itemView.xh.visibility = View.GONE
                                holder.itemView.santai.visibility = View.GONE
                            }
                            1 -> {
                                holder.itemView.ll.visibility = View.VISIBLE
                                holder.itemView.ch.visibility = View.GONE
                                holder.itemView.dd.visibility = View.VISIBLE
                                holder.itemView.xh.visibility = View.GONE
                                holder.itemView.santai.visibility = View.GONE
                            }
                            2 -> {
                                holder.itemView.ll.visibility = View.VISIBLE
                                holder.itemView.ch.visibility = View.GONE
                                holder.itemView.dd.visibility = View.GONE
                                holder.itemView.xh.visibility = View.VISIBLE
                                holder.itemView.santai.visibility = View.GONE
                            }
                            3 -> {
                                holder.itemView.ch.visibility = View.GONE
                                holder.itemView.dd.visibility = View.GONE
                                holder.itemView.xh.visibility = View.GONE
                                holder.itemView.ll.visibility = View.GONE
                                holder.itemView.santai.visibility = View.GONE
                                holder.itemView.emty_v.visibility = View.VISIBLE
                            }
                            4 -> {
                                holder.itemView.ch.visibility = View.GONE
                                holder.itemView.dd.visibility = View.GONE
                                holder.itemView.xh.visibility = View.GONE
                                holder.itemView.ll.visibility = View.VISIBLE
                                holder.itemView.santai.visibility = View.VISIBLE
                                when {
                                    list2[position].endstate == 0 -> holder.itemView.santai.background = resources.getDrawable(R.mipmap.icon_santai1)
                                    list2[position].endstate == 1 -> holder.itemView.santai.background = resources.getDrawable(R.mipmap.icon_santai2)
                                    else -> holder.itemView.santai.background = resources.getDrawable(R.mipmap.icon_santai3)
                                }
                            }
                        }

                        setcolor(list2[position].contents, holder.itemView.content_tv)
                        holder.itemView.xh.text = "${position + 1}."
                    }
                }
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChildAdapter.Holder {
            val view = LayoutInflater.from(this@NewSixTaskDetailActivity).inflate(R.layout.calender_taskfx_de_list_item, parent, false)
            return Holder(view)
        }


        inner class Holder(itemview: View) : RecyclerView.ViewHolder(itemview)

    }

    private fun uploadCalendernote(id: Int) {
        val list = App.getDBcApplication().getCalenderNoteDetailData(userid, schSourceDesc, false)
        val listjsonObject = JSONObject()
        val listjsonArray = JSONArray()
        try {
            for (bean in list) {
                val js = JSONObject()
                if (id == bean.id) {
                    js.put("id", bean.id)
                    js.put("titleId", bean.titleId)
                    js.put("uid", bean.uid)
                    js.put("titles", bean.titles)
                    js.put("imgPath", bean.imgPath)
                    js.put("imgUrl", bean.imgUrl)
                    js.put("shareUrl", bean.shareUrl)
                    js.put("contents", bean.contents)
                    js.put("nums", bean.nums)
                    js.put("style", bean.style)
                    js.put("endstate", bean.endstate)
                    js.put("lType", bean.ltype)
                    js.put("orderId", bean.orderId)
                    js.put("createTime", bean.createTime)
                    js.put("changeTime", bean.changeTime)
                    js.put("cpath", bean.cpath)
                    js.put("curl", bean.curl)
                    js.put("sdesc", bean.sdesc)
                    js.put("localIds", bean.localIds)
                    js.put("remark", bean.remark)
                    js.put("remark1", bean.remark1)
                    js.put("remark2", bean.remark2)
                    js.put("remark3", bean.remark3)
                    js.put("remark4", bean.remark4)
                    js.put("remark4", bean.remark5)
                    js.put("remark4", bean.remark6)
                    js.put("updateState", 2)
                }
                listjsonArray.put(js)
            }
            if (list.size > 0) {
                listjsonObject.put("timetable", listjsonArray)
            }


            val httpUtils = HttpUtils(10000)
            val params = RequestParams()
            params.addBodyParameter("data", listjsonObject?.toString())
            httpUtils.send(HttpRequest.HttpMethod.POST, URLConstants.日程清单同步数据, params,
                    object : RequestCallBack<String>() {

                        override fun onFailure(e: HttpException, msg: String) {}

                        override fun onSuccess(responseInfo: ResponseInfo<String>) {
                            if (!TextUtils.isEmpty(responseInfo.result)) {
                                val gson = Gson()
                                val bean = gson.fromJson(responseInfo.result, CalenderNoteSynBean::class.java)
                                if (bean.status == 0) {
                                    val listBeanList = bean.list

                                    for (listBean in listBeanList) {
                                        when {
                                            listBean.dataState == 1 -> //新增
                                                when {
                                                    listBean.state == 0 -> {//成功
                                                        //修改id和状态值
                                                        App.getDBcApplication().updateCalenderNoteDetailId(listBean.id, listBean.calendId, userid)
                                                        for (i in list.indices) {
                                                            val beanitem = list[i]
                                                            if (listBean.id == beanitem.id) {
                                                                list[i].setId(listBean.calendId)
                                                            }
                                                        }
                                                        App.getDBcApplication().updateCalenderNoteDetailState("", listBean.calendId, userid, 0, true)
                                                    }
                                                    listBean.state == 1 -> //失败  可以不操作,但是避免意外
                                                        //更改状态为1
                                                        App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, userid, 1, true)
                                                    listBean.state == 2 -> //异常
                                                        App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, userid, -1, true)
                                                }
                                            listBean.dataState == 2 -> //修改
                                                when {
                                                    listBean.state == 0 -> //成功
                                                        //修改该id状态值
                                                        App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, userid, 0, true)
                                                    listBean.state == 1 -> //失败
                                                        //更改状态为2
                                                        App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, userid, 2, true)
                                                    listBean.state == 2 -> //异常
                                                        App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, userid, -1, true)
                                                }
                                            listBean.dataState == 3 -> //删除
                                                when {
                                                    listBean.state == 0 -> //成功
                                                        //删除该id的清单
                                                        App.getDBcApplication().deleteCalenderNoteTitledetailData(listBean.id, userid, true)
                                                    listBean.state == 1 -> //失败
                                                        //更改状态为3
                                                        App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, userid, 3, true)
                                                    listBean.state == 2 -> //异常
                                                        App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, userid, -1, true)
                                                }
                                        }
                                    }
                                }
                            }
                        }
                    })
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }


    private fun clickEndstate(position: Int, type: Int, id: Int, endtype: Int, image: ImageView) {
        val progressUtil = ProgressUtil()
        progressUtil.ShowProgress(context, true, true, "正在修改")
        val httpUtils = HttpUtils(5000)
        val params = RequestParams()
        params.addBodyParameter("uid", userid)
        params.addBodyParameter("type", type.toString() + "")
        params.addBodyParameter("id", id.toString() + "")
        httpUtils.send(HttpRequest.HttpMethod.POST, URLConstants.接收方任务子项结束, params, object : RequestCallBack<String>() {
            override fun onSuccess(responseInfo: ResponseInfo<String>) {
                if (!TextUtils.isEmpty(responseInfo.result)) {
                    val gson = Gson()
                    val bean = gson.fromJson<EndBean>(responseInfo.result, EndBean::class.java)
                    if (bean.status == 0) {
//                        if (schRemark1 == "1") {
//                            App.getDBcApplication().updateCalenderNoteDetailEndstate(id, type, schSourceDesc, userid, true)
//                        }
                        if (endtype == 0) {
                            if (type == 0) {
                                image.background = resources.getDrawable(R.mipmap.btn_qd_unfinish_c)
                            } else {
                                image.background = resources.getDrawable(R.mipmap.btn_qd_finish_c)
                            }
                        } else if (endtype == 1) {
                            when (type) {
                                0 -> image.background = resources.getDrawable(R.mipmap.icon_santai1)
                                1 -> image.background = resources.getDrawable(R.mipmap.icon_santai2)
                                else -> image.background = resources.getDrawable(R.mipmap.icon_santai3)
                            }
                        }

                        adapter.updateEndstate(position, type)
                    }
                } else {
                    Toast.makeText(this@NewSixTaskDetailActivity, "网络异常", Toast.LENGTH_SHORT).show()
                }
                progressUtil.dismiss()
            }

            override fun onFailure(e: HttpException, s: String) {
                progressUtil.dismiss()
                Toast.makeText(this@NewSixTaskDetailActivity, "网络异常", Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun getUrlTime() {
        val httpUtils = HttpUtils(5000)
        val params = RequestParams()
        if (puid == "0" || puid == "") {
            puid = userid
        }
        params.addBodyParameter("cUid", puid)
        params.addBodyParameter("titleId", schSourceDesc)
        httpUtils.send(HttpRequest.HttpMethod.POST, URLConstants.链接成员信息查询, params, object : RequestCallBack<String>() {
            override fun onSuccess(responseInfo: ResponseInfo<String>) {
                if (!TextUtils.isEmpty(responseInfo.result)) {
                    val gson = Gson()
                    val bean = gson.fromJson<FindUrlTimeBean>(responseInfo.result, FindUrlTimeBean::class.java)
                    if (bean.status == 0) {
                        var list = bean.list
                        var content = "最近访问时间:\n"
                        list.forEach {
                            content += it.changeTime.replace("T", " ") + "   " + it.uNickName + "\n"
                            persons.text = content
                        }
                    }
                }
            }

            override fun onFailure(e: HttpException, s: String) {
            }
        })
    }


    private fun updateUrlTime() {
        val httpUtils = HttpUtils(5000)
        val params = RequestParams()
        params.addBodyParameter("uid", userid)
        params.addBodyParameter("titleId", schSourceDesc)
        httpUtils.send(HttpRequest.HttpMethod.POST, URLConstants.链接浏览时间修改, params, object : RequestCallBack<String>() {
            override fun onSuccess(responseInfo: ResponseInfo<String>) {
            }

            override fun onFailure(e: HttpException, s: String) {
            }
        })
    }

    //设置双#号包裹的文字颜色
    private fun setcolor(content: String, editText: TextView) {
        if (content.length > 1) {
            val builder = SpannableStringBuilder(content)
            val integerList = ArrayList<Int>()
            var index = 0
            val count = hit(content, "#")
            if (count > 1) {
                if (count % 2 == 0) {
                    for (i in 0 until count) {
                        index = if (i == 0) {
                            content.indexOf("#")
                        } else {
                            content.indexOf("#", index + 1)
                        }
                        integerList.add(index)
                    }
                    for (i in integerList.indices) {
                        if (i > 0) {
                            if (i % 2 != 0) {
                                val span = ForegroundColorSpan(Color.parseColor("#df7926"))
                                builder.setSpan(span, integerList[i - 1], integerList[i] + 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
                            }
                        }
                    }
                    editText.text = builder
                } else {
                    for (i in 0 until count - 1) {
                        index = if (i == 0) {
                            content.indexOf("#")
                        } else {
                            content.indexOf("#", index + 1)
                        }
                        integerList.add(index)

                    }
                    for (i in integerList.indices) {
                        if (i > 0) {
                            if (i % 2 != 0) {
                                val span = ForegroundColorSpan(Color.parseColor("#df7926"))
                                builder.setSpan(span, integerList[i - 1], integerList[i] + 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
                            }
                        }
                    }
                    editText.text = builder
                }
            } else {
                editText.text = content
            }
        } else {
            editText.text = content
        }
        editText.setLineSpacing(20f, 1.5f)
    }

    /**
     * @param a 被匹配的长字符串
     * @param b 匹配的短字符串
     * @return 匹配次数
     */
    fun hit(a: String, b: String): Int {
        if (a.length < b.length) {
            return 0
        }
        val a_t = a.toCharArray()
        var count = 0

        for (i in 0 until a.length) {
            val buffer = StringBuffer()
            for (j in 0 until b.length) {
                buffer.append(a_t[i + j])
            }
            if (buffer.toString() == b) {
                count++
            }
        }

        return count
    }

    class EndBean {
        var status: Int = 0
        var downTime: String = ""
        var listOpdata: Any? = null
        var message: String = ""
        var list2: Any? = null
        var list: Any? = null
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        isLocal = 1

        list4 = App.getDBcApplication().getCalenderNoteDetailData(userid, schSourceDesc, false)

        loadData()
    }


    private fun load() {
        val httpUtils0 = HttpUtils(5000)
        val params0 = RequestParams()
        params0.addBodyParameter("titleId", schSourceDesc)
        params0.addBodyParameter("type", "5")
        params0.addBodyParameter("uId", cUid.toString())
        params0.addBodyParameter("nowPage", "1")
        params0.addBodyParameter("pageNum", "2000")
        params0.addBodyParameter("id", id.toString() + "")
        params0.addBodyParameter("changeTime", "")
        httpUtils0.send(HttpRequest.HttpMethod.POST, URLConstants.清单留言查询留言主表, params0, object : RequestCallBack<String>() {
            override fun onSuccess(responseInfo: ResponseInfo<String>) {
                if (!TextUtils.isEmpty(responseInfo.result)) {
                    val gson = Gson()
                    val noteLYBean = gson.fromJson(responseInfo.result, NoteLYBean::class.java)
                    if (noteLYBean.status == 0) {
                        itemsBeanList = noteLYBean.page.items
                        lyadapter()
                    }
                }
            }

            override fun onFailure(e: HttpException, s: String) {

            }
        })
    }

    internal var itemsBeanList: List<NoteLYBean.PageBean.ItemsBean> = ArrayList()
    private fun lyadapter() {
        Collections.sort<NoteLYBean.PageBean.ItemsBean>(itemsBeanList) { lhs, rhs -> DateUtil.parseDateTimeSs(rhs.changeTime.replace("T", " "))!!.compareTo(DateUtil.parseDateTimeSs(lhs.changeTime.replace("T", " "))!!) }
        var listAdapter = ListAdapter(itemsBeanList)
        listview.adapter = listAdapter
        listAdapter.notifyDataSetChanged()

        if (itemsBeanList.isNotEmpty()) {
            ly_sum.text = "留言(${itemsBeanList.size})"
        }

    }


    internal inner class ListAdapter(list: List<NoteLYBean.PageBean.ItemsBean>) : BaseAdapter() {

        var list: List<NoteLYBean.PageBean.ItemsBean> = ArrayList()

        init {
            this.list = list
        }

        override fun getCount(): Int {
            return list.size
        }

        override fun getItem(position: Int): Any? {
            return null
        }

        override fun getItemId(position: Int): Long {
            return 0
        }

        @SuppressLint("SetTextI18n")
        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
            var convertView = convertView
            val holder: ViewHolder
            if (convertView == null) {
                holder = ViewHolder()
                convertView = LayoutInflater.from(context).inflate(R.layout.new_my_ly_item, parent, false)

                holder.imageView = convertView!!.findViewById<View>(R.id.lys_icon) as ImageView
                holder.name = convertView.findViewById<View>(R.id.lys_name) as TextView
                holder.time = convertView.findViewById<View>(R.id.lys_time) as TextView
                holder.message = convertView.findViewById<View>(R.id.lys_message) as TextView
                holder.ly_item_ll = convertView.findViewById<View>(R.id.ly_item_ll) as LinearLayout

                convertView.tag = holder
            } else {
                holder = convertView.tag as ViewHolder
            }
            val options = DisplayImageOptions.Builder()
                    .showStubImage(R.mipmap.img_null_smal)
                    .showImageForEmptyUri(R.mipmap.img_null_smal)
                    .showImageOnFail(R.mipmap.img_null_smal)
                    .cacheInMemory(true)
                    .cacheOnDisc(true)
                    .build()

            val imageurl = URLConstants.HOST + "/TbDU_showImage.htm?imageName=" + list[position].lyTitleImg + "&imageType=2&imageSizeType=3"

            ImageLoader.getInstance().displayImage(imageurl, holder.imageView!!, options)

            holder.time!!.text = list[position].changeTime.replace("T", " ") + " " + list[position].reamrk1
            holder.name!!.text = list[position].lyName
            holder.message!!.text = list[position].mess
            return convertView
        }


        internal inner class ViewHolder {
            var imageView: ImageView? = null
            var name: TextView? = null
            var time: TextView? = null
            var message: TextView? = null
            var ly_item_ll: LinearLayout? = null
        }


    }


    private fun alterImportantDialog(context: Context, message: String, type: Int, position: Int) {
        val dialog = Dialog(context, R.style.dialog_translucent_adjustPan)
        val window = dialog.window
        val params = window!!.attributes// 获取LayoutParams
        params.alpha = 0.92f
        window.setGravity(Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL)
        window.attributes = params// 设置生效

        val fac = LayoutInflater.from(context)
        val more_pop_menu = fac.inflate(R.layout.add_reply_dialogs, null)
        dialog.setCanceledOnTouchOutside(true)
        dialog.setContentView(more_pop_menu)
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT
        params.width = ViewGroup.LayoutParams.MATCH_PARENT
        dialog.show()

        alterImportantDialogOnClick(context, dialog, more_pop_menu, message, type, position)
    }

    internal inner class alterImportantDialogOnClick @SuppressLint("NewApi")
    constructor(private val context: Context, private val dialog: Dialog, private val view: View, private val message: String, var type: Int, var position: Int) : View.OnClickListener {
        private var addnote_tv: TextView? = null
        private var copy_tv: TextView? = null
        private var canel_tv: TextView? = null

        init {
            initview()
        }

        private fun initview() {
            copy_tv = view.findViewById<View>(R.id.copy_tv) as TextView
            copy_tv!!.setOnClickListener(this)
            if (type == 1) {
                copy_tv!!.text = "复制留言内容"
            }
            canel_tv = view.findViewById<View>(R.id.canel_tv) as TextView
            canel_tv!!.setOnClickListener(this)
            addnote_tv = view.findViewById<View>(R.id.addnote_tv) as TextView
            addnote_tv!!.text = "加入日程子项"
            val delete_tv = view.findViewById<View>(R.id.delete_tv) as TextView
            if (cUid.toString() == userid && type == 1) {
                delete_tv.visibility = View.VISIBLE
                addnote_tv!!.visibility = View.VISIBLE
            } else {
                delete_tv.visibility = View.GONE
                addnote_tv!!.visibility = View.GONE
            }
            delete_tv.setOnClickListener {
                dialog.dismiss()
                val bean = itemsBeanList[position]
                delete(2, bean.id)
            }
            addnote_tv!!.setOnClickListener {

                val newid = App.getDBcApplication().calenderMinId - 1
                val bean = CalenderNoteBean.PageBean.ItemsBean()
                bean.titleId = schSourceDesc
                bean.uid = Integer.valueOf(userid)
                bean.id = newid
                bean.style = stylee
                bean.changeTime = DateUtil.nowTime()
                bean.createTime = DateUtil.nowTime()
                bean.ltype = 0
                bean.orderId = if (schSourceType == "5" || schRemark1 == "1") list3.size else list2.size
                bean.endstate = 0
                bean.remark = ""
                bean.contents = message
                bean.titles = schContent
                bean.imgPath = title_img
                bean.imgUrl = ""
                bean.cpath = ""
                bean.curl = ""
                bean.sdesc = ""
                bean.nums = ""
                bean.localIds = DateUtil.nowTime2()
                bean.shareUrl = ""
                bean.remark1 = ""
                bean.remark2 = ""
                bean.remark3 = ""
                bean.remark4 = ""
                bean.remark5 = ""
                bean.remark6 = ""

                App.getDBcApplication().saveCalederNoteDetailData(bean)
                App.getDBcApplication().updateCalenderNoteDetailState(schContent, bean.id, userid, 1, false)

                Toast.makeText(context, "加入成功", Toast.LENGTH_SHORT).show()
                uploadCalendernote()
                dialog.dismiss()
            }
        }

        override fun onClick(v: View) {
            when (v.id) {
                R.id.copy_tv -> {
                    // 为了兼容低版本我们这里使用旧版的android.text.ClipboardManager，虽然提示deprecated，但不影响使用。
                    val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                    // 将文本内容放到系统剪贴板里。
                    cm.text = message
                    Toast.makeText(context, "已复制", Toast.LENGTH_SHORT).show()
                    dialog.dismiss()
                }
                R.id.canel_tv -> dialog.dismiss()
            }
        }
    }

    private fun delete(type: Int, id: Int) {
        val progressUtil = ProgressUtil()
        progressUtil.ShowProgress(context, true, true, "正在删除...")
        val httpUtils = HttpUtils(3000)
        val params = RequestParams()
        params.addBodyParameter("uId", userid)
        params.addBodyParameter("type", type.toString() + "")
        params.addBodyParameter("id", id.toString() + "")
        params.addBodyParameter("titleId", schSourceDesc)
        httpUtils.send(HttpRequest.HttpMethod.POST, URLConstants.清单留言删除主留言信息, params, object : RequestCallBack<String>() {
            override fun onSuccess(responseInfo: ResponseInfo<String>) {
                load()
                progressUtil.dismiss()
            }

            override fun onFailure(e: HttpException, s: String) {
                Toast.makeText(context, "网络异常", Toast.LENGTH_SHORT).show()
                progressUtil.dismiss()
            }
        })
    }

    internal var list: MutableList<CalenderNoteBean.PageBean.ItemsBean> = ArrayList()
    private fun uploadCalendernote() {
        list = App.getDBcApplication().getCalenderNoteDetailData(userid, schSourceDesc, false)
        val listjsonObject = JSONObject()
        val listjsonArray = JSONArray()
        try {
            for (bean in list) {
                val js = JSONObject()
                js.put("id", bean.id)
                js.put("titleId", bean.titleId)
                js.put("uid", bean.uid)
                js.put("titles", bean.titles)
                js.put("imgPath", bean.imgPath)
                js.put("imgUrl", bean.imgUrl)
                js.put("shareUrl", bean.shareUrl)
                js.put("contents", bean.contents)
                js.put("nums", bean.nums)
                js.put("style", bean.style)
                js.put("endstate", bean.endstate)
                js.put("lType", bean.ltype)
                js.put("orderId", bean.orderId)
                js.put("createTime", bean.createTime)
                js.put("changeTime", bean.changeTime)
                js.put("cpath", bean.cpath)
                js.put("curl", bean.curl)
                js.put("sdesc", bean.sdesc)
                js.put("localIds", bean.localIds)
                js.put("remark", bean.remark)
                js.put("remark1", bean.remark1)
                js.put("remark2", bean.remark2)
                js.put("remark3", bean.remark3)
                js.put("remark4", bean.remark4)
                js.put("remark4", bean.remark5)
                js.put("remark4", bean.remark6)
                js.put("updateState", if (bean.id < 0) 1 else App.getDBcApplication().getCalenderNoteDetailState(bean.titleId, userid, bean.id))
                listjsonArray.put(js)
            }
            if (list.size > 0) {
                listjsonObject.put("timetable", listjsonArray)
            }


            val httpUtils = HttpUtils(10000)
            val params = RequestParams()
            params.addBodyParameter("data", listjsonObject.toString())
            httpUtils.send(HttpRequest.HttpMethod.POST, URLConstants.日程清单同步数据, params,
                    object : RequestCallBack<String>() {

                        override fun onFailure(e: HttpException, msg: String) {
                            loadData()
                        }

                        override fun onSuccess(responseInfo: ResponseInfo<String>) {
                            if (!TextUtils.isEmpty(responseInfo.result)) {
                                val gson = Gson()
                                val bean = gson.fromJson(responseInfo.result, CalenderNoteSynBean::class.java)
                                if (bean.status == 0) {
                                    val listBeanList = bean.list


                                    for (listBean in listBeanList) {
                                        when {
                                            listBean.dataState == 1 -> //新增
                                                when {
                                                    listBean.state == 0 -> {//成功
                                                        //修改id和状态值
                                                        App.getDBcApplication().updateCalenderNoteDetailId(listBean.id, listBean.calendId, userid)
                                                        for (i in list.indices) {
                                                            val beanitem = list.get(i)
                                                            if (listBean.id == beanitem.id) {
                                                                list.get(i).setId(listBean.calendId)
                                                            }
                                                        }
                                                        App.getDBcApplication().updateCalenderNoteDetailState("", listBean.calendId, userid, 0, true)
                                                    }
                                                    listBean.state == 1 -> //失败  可以不操作,但是避免意外
                                                        //更改状态为1
                                                        App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, userid, 1, true)
                                                    listBean.state == 2 -> //异常
                                                        App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, userid, -1, true)
                                                }
                                            listBean.dataState == 2 -> //修改
                                                when {
                                                    listBean.state == 0 -> //成功
                                                        //修改该id状态值
                                                        App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, userid, 0, true)
                                                    listBean.state == 1 -> //失败
                                                        //更改状态为2
                                                        App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, userid, 2, true)
                                                    listBean.state == 2 -> //异常
                                                        App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, userid, -1, true)
                                                }
                                            listBean.dataState == 3 -> //删除
                                                when {
                                                    listBean.state == 0 -> //成功
                                                        //删除该id的清单
                                                        App.getDBcApplication().deleteCalenderNoteTitledetailData(listBean.id, userid, true)
                                                    listBean.state == 1 -> //失败
                                                        //更改状态为3
                                                        App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, userid, 3, true)
                                                    listBean.state == 2 -> //异常
                                                        App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, userid, -1, true)
                                                }
                                        }
                                    }
                                }
                            }
                            loadData()
                        }
                    })
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }
}